package com.ukao.steward.ui.valetRunners.bingCard;


import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ukao.steward.R;
import com.ukao.steward.base.MvpFragment;
import com.ukao.steward.bean.SearchUserBean;
import com.ukao.steward.bean.UserInfoCard;
import com.ukao.steward.dialog.BingHintDialogFragment;
import com.ukao.steward.dialog.BingStateDialogFragment;
import com.ukao.steward.listener.DialogSubmitListener;
import com.ukao.steward.pesenter.valetRunners.ClientPesenter;
import com.ukao.steward.ui.main.HomeFragment;
import com.ukao.steward.ui.valetRunners.createOrder.GuestFragment;
import com.ukao.steward.ui.valetRunners.storeCreatOrder.StoreClientInfoFragment;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.ImageUtils;
import com.ukao.steward.util.RegularUtils;
import com.ukao.steward.view.valetRunners.ClientView;
import com.ukao.steward.widget.ShapedImageView;
import com.ukao.steward.widget.StateButton;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 客户信息
 */
public class ClientFragment extends MvpFragment<ClientPesenter> implements ClientView {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    Unbinder unbinder;
    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.title_layout)
    RelativeLayout titleLayout;
    @BindView(R.id.cardName)
    TextView cardName;
    @BindView(R.id.cardDiscountName)
    TextView cardDiscountName;
    @BindView(R.id.attr)
    TextView attr;
    @BindView(R.id.cardNo)
    TextView cardNo;
    @BindView(R.id.balance)
    TextView balance;
    @BindView(R.id.headimgPath)
    ShapedImageView headimgPath;
    @BindView(R.id.product_name)
    TextView name;
    @BindView(R.id.phone)
    TextView phone;
    @BindView(R.id.use_balance)
    TextView useBalance;
    @BindView(R.id.use_cardNo)
    TextView useCardNo;
    @BindView(R.id.use_cardLevel)
    TextView useCardLevel;
    @BindView(R.id.use_cardstate)
    TextView useCardstate;
    @BindView(R.id.bing_btn)
    StateButton bingBtn;

    private Handler mHandler = new Handler();
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private UserInfoCard muserInfoCard;
    private boolean isBing;/*是否绑定*/
    private SearchUserBean mSearchUserBean;
    private boolean isBinding;
    private boolean isStoreCreatOrderEnter;

    public static ClientFragment newInstance(Parcelable muserInfoCard,  SearchUserBean mSearchUserBean,boolean  isStoreCreatOrderEnter   ) {
        ClientFragment fragment = new ClientFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARG_PARAM1, muserInfoCard);
        args.putParcelable(ARG_PARAM2, mSearchUserBean);
        args.putBoolean("isStoreCreatOrderEnter",isStoreCreatOrderEnter);
        fragment.setArguments(args);
        return fragment;
    }   public static ClientFragment newInstance(Parcelable muserInfoCard  , boolean isStoreCreatOrderEnter ) {
        ClientFragment fragment = new ClientFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARG_PARAM1, muserInfoCard);
        args.putBoolean("isStoreCreatOrderEnter",isStoreCreatOrderEnter);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
             muserInfoCard = getArguments().getParcelable(ARG_PARAM1);
            mSearchUserBean = getArguments().getParcelable(ARG_PARAM2);
            isStoreCreatOrderEnter=getArguments().getBoolean("isStoreCreatOrderEnter");


        }
    }

    @Override
    protected ClientPesenter createPresenter() {
        return new ClientPesenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_client, container, false);
        unbinder = ButterKnife.bind(this, view);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        fillData();
    }


    @Override
    protected void initView() {

        title.setText("客戶信息");
        titleLayout.setBackgroundColor(getColors(R.color.colorPrimary));

    }

    private void fillData( ) {
        if (!CheckUtils.isNull(mSearchUserBean)){
            useBalance.setText("￥"+CheckUtils.isEmptyNumber(mSearchUserBean.getBalance()));
            useCardLevel.setText(CheckUtils.isEmptyString(mSearchUserBean.getCardName()));
            String    cardNo=CheckUtils.isEmpty(mSearchUserBean.getRfidNo())?mSearchUserBean.getCardNo(): mSearchUserBean.getRfidNo();
            useCardNo.setText(cardNo);
            name.setText(CheckUtils.isEmptyString(mSearchUserBean.getName()));
            phone.setText(CheckUtils.isEmptyString(mSearchUserBean.getPhone()));
            ImageUtils.loadHeadImage(_mActivity,mSearchUserBean.getHeadimgPath(),headimgPath);
            isBinding=mSearchUserBean.getIsBinding();
            if (isBinding){
            String    cardNos=CheckUtils.isEmpty(mSearchUserBean.getRfidNo())?mSearchUserBean.getCardNo(): mSearchUserBean.getRfidNo();
                setBingInfo(CheckUtils.isEmptyString(mSearchUserBean.getCardName()), cardNos, "", mSearchUserBean.getCardDiscountName(), CheckUtils.isEmptyNumber(mSearchUserBean.getBalance()));
            }
            setBingState();

        }

        fillSearchData(); /*搜索用户信息，如果搜索用户信息未绑定就显示卡的数据*/


    }

    private void fillSearchData() {
        if (!CheckUtils.isNull(muserInfoCard)&&!isBinding) {
            String    cardNos=CheckUtils.isEmpty(muserInfoCard.getRfidNo())?muserInfoCard.getCardNo(): muserInfoCard.getRfidNo();
            setBingInfo(CheckUtils.isEmptyString(muserInfoCard.getCardName()),cardNos , CheckUtils.isEmpty(muserInfoCard.getAttr())? "": "所属："+ muserInfoCard.getAttr(),muserInfoCard.getCardDiscountName(), CheckUtils.isEmptyNumber(muserInfoCard.getBalance()));
            isBinding=muserInfoCard.getIsBinding();
            if (isBinding){
                useBalance.setText("￥"+CheckUtils.isEmptyNumber(muserInfoCard.getBalance()));
                useCardLevel.setText(CheckUtils.isEmptyString(muserInfoCard.getCardName()));
                useCardNo.setText(CheckUtils.isEmpty(muserInfoCard.getRfidNo())?muserInfoCard.getCardNo(): muserInfoCard.getRfidNo());
                name.setText(CheckUtils.isEmptyString(muserInfoCard.getName()));
                phone.setText(CheckUtils.isEmptyString(muserInfoCard.getPhone()));
                ImageUtils.loadHeadImage(_mActivity,muserInfoCard.getHeadimgPath(),headimgPath);
                setBingState();
            }

        }
    }

    private void setBingState() {
        if (isBinding){
            bingBtn.setText("下一步");
            useCardstate.setText("已绑定会员卡");
            useCardstate.setTextColor(getColors(R.color.greend_color));
        }else{
            bingBtn.setText("绑卡");
            useCardstate.setText("未绑定实体会员卡");
            useCardstate.setTextColor(getColors(R.color.pink_backgroud));
        }
    }



    @OnClick({R.id.back_btn, R.id.bing_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                closeOtherFragment();
                break;
            case R.id.bing_btn:
                if(isBinding) {
                    if (muserInfoCard!=null)
                    mvpPresenter.queryKeyword(muserInfoCard.getPhone());
                }else  if ( !CheckUtils.isNull(mSearchUserBean)&&!mSearchUserBean.getIsBinding()   ){/*搜索进入*/
                    BingHintDialogFragment mBingHintDialog = BingHintDialogFragment.newInstance(resources.getString(R.string.iscard_bing_hite), "");
                    mBingHintDialog.setOnSubmitClickListener(mDialogListener);
                    mBingHintDialog.show(getChildFragmentManager(),BingHintDialogFragment.class.getName());
                }



                break;
        }
    }

    private DialogSubmitListener mDialogListener = new DialogSubmitListener() {
        @Override
        public void onSubmitClick(int parent, Object message) {
            switch (parent){
                case R.id.edit_name_submit :
                    if (!CheckUtils.isNull(muserInfoCard)){
                        mvpPresenter.cardBinding(mSearchUserBean.getUserId()+"",muserInfoCard.getRefidId()+"");
            }
                    break;

            }



        }
    };

    @Override
    public void queryPhoneSucced(SearchUserBean model) {
        if (model.getIsRegister()!=0){/*注册过得用户*/
            if (isStoreCreatOrderEnter){
                start(StoreClientInfoFragment.newInstance(model,""), SINGLETASK);
            }else{
                start(GuestFragment.newInstance(model,""),SINGLETASK);
            }

        }

        }

    /**
     * 绑卡成功
     */
    @Override
    public void cardBindingSucceed(String  rfidNo) {
        if (!CheckUtils.isNull(mSearchUserBean)){
            mvpPresenter.queryKeyword(rfidNo,"");

        }
        final BingStateDialogFragment mBingStateDialog = BingStateDialogFragment.newInstance("", "");
        mBingStateDialog.show(getChildFragmentManager(),BingStateDialogFragment.class.getName());
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mBingStateDialog.dismiss();
            }
        }, 2000);

    }

    @Override
    public void queryKeyword(UserInfoCard mUserInfoCard) {
        this.muserInfoCard=mUserInfoCard;
        fillSearchData();
    }




    /**
     * 设置卡的信息
     * @param emptyString
     * @param emptyString2
     * @param text
     * @param emptyString3
     * @param emptyNumber
     */
    private void setBingInfo(String emptyString, String emptyString2, String text, String emptyString3, String emptyNumber) {
        cardName.setText(emptyString);
        cardNo.setText(RegularUtils.formatNum(emptyString2));
        attr.setText(text);
        cardDiscountName.setText(emptyString3);
        balance.setText("￥"+emptyNumber);
    }



    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        mHandler.removeCallbacksAndMessages(null);
    }
    @Override
    public boolean onBackPressedSupport() {
        closeOtherFragment();

        return true;
    }

    private void closeOtherFragment() {
        try{

           if (isAdded()&& findFragment(ClientFragment.class)!=null){
               popTo(HomeFragment.class,false);
           }

        }catch (Exception e){

        }

        }

}
